var grid;
var form;
var form1;
$(function () {

    //加载该页面前，先判断该模块的权限
    //获取当前登录的用户的权限
    var permission = document.cookie.split(";")[1].split("=")[1];
    var b = String(permission).split('');
    for (var i = 0; i < b.length; i++) {
        console.log(b[i]);
    }
    var moudle31 = b[8];
    //如果模块权限为1，即只能查询此模块下的数据，不能进行修改（禁用和重置密码不能使用）
    //系统管理
    flag = true;
    if (moudle31 == 1) {
        $("#addBtn").css('display', 'none');
        flag = false;
    }

    var pageNo = 1;
    var pageSize = 5;
    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";

    //初始化数据表格
    grid = $(grid_selector).jqGrid({
        datatype: "json",
        url: 'find.action',
        mtype: 'POST',
        page: pageNo,
        postData: {
            'id': $("#i1").val(),
            'customerName': $("#i2").val(),
            'customerType': $("#s1 option:selected").text(),
            'UID': $("#i3").val(),
        },
        height: 380,
        width: 300,
        colNames: ['删除', '证件号码', '客户编号', '客户名称', '客户类型', "所属银行", "客户状态", "创建时间", "抵押物名称"],
        colModel: [
            {
                name: 'action', index: '', fixed: true, sortable: false, resize: false,
                formatter: function (cellvalue, options, rowObject) {
                    var txt;
                    var shel;
                    if (flag == false) {
                        return "<button disabled class='btn btn-warning btn-xs' onclick='deleteEdit(\"" + rowObject.id + "\")'><i class='fa fa-edit button-in-i'></i>删除</button>";
                    } else {
                        return "<button class='btn btn-warning btn-xs' onclick='deleteEdit(\"" + rowObject.id + "\")'><i class='fa fa-edit button-in-i'></i>删除</button>";
                    }
                }
            },
            {name: 'UID', index: 'UID', sortable: false, align: 'center'},
            {name: 'id', index: 'id', sortable: false, align: 'center'},
            {
                name: 'customerName', index: 'customerName', sortable: false, align: 'center',
                formatter: function (cellvalue, options, rowObject) {
                    if (flag == false) {
                        return "<button disabled href='javascript:void(0);' onclick='turnOut(\"" + rowObject.id + "\")'>" + cellvalue + "</button>";
                    } else {
                        return "<button href='javascript:void(0);' onclick='turnOut(\"" + rowObject.id + "\")'>" + cellvalue + "</button>";
                    }
                }
            },

            {name: 'customerType', index: 'customerType', sortable: false, align: 'center'},
            {name: 'bankName', index: 'bankName', sortable: false, align: 'center'},
            {name: 'customerState', index: 'customerState', sortable: false, align: 'center'},
            {name: 'createTime', index: 'createTime', sortable: false, align: 'center'},
            {name: 'pledgeName', index: 'pledgeName', sortable: false, align: 'center'},
        ],
        viewrecords: true,
        rowNum: pageSize,
        rownumbers: false,//添加左侧行号
        rowList: [5, 10, 15],
        pager: pager_selector,
        altRows: true,
        multiselect: false,
        loadComplete: function (data) {
            var table = this;

            setTimeout(function () {
                updatePagerIcons(table);
            }, 0);
            var h = $(window).height() - ($('#grid-pager')[0].offsetHeight + 15) - ($('.result-table .box')[0].offsetTop + $('.content .col-xs-12')[0].offsetTop + $('.ui-jqgrid-bdiv')[0].offsetTop + 3);
            $('.ui-jqgrid-bdiv').height(h);
        },
        autowidth: true,
        jsonReader: jsonReader,   // json中代表实际模型数据的入口
        rownumWidth: 55,
        prmNames: prmNames,
        recordtext: "显示 {0} - {1} 条 , 共 {2} 条",
        emptyrecords: "没有记录",
        loadtext: "正在加载...",
        pgtext: "第 {0} 页  ,共 {1} 页"
    });
    //初始化分页条
    showNavGrid(grid_selector, pager_selector);
    //初始化信息校验表单
    form = $("#addform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });
    form1 = $("#Editform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });

    $("#addBtn").click(function () {
        openAdd();
    });

    $("#addNewBtn").click(function () {
        openNewAdd();
    });

    $("#openEdit").click(function () {
        openEdit(str);
    });
    $("#clearBtn").click(function () {
        $("#i1").val(null).trigger("change");
        $("#i2").val(null).trigger("change");
        $("#s1").val(null).trigger("change");
        $("#i3").val(null).trigger("change");
    });

    $("#queryBtn").click(function () {
        var filters = {
            'id': $("#i1").val(),
            'customerName': $("#i2").val(),
            'customerType': $("#s1 option:selected").text(),
            'UID': $("#i3").val(),
        }
        grid.jqGrid("setGridParam", {postData: filters, page: 1});
        grid.trigger('reloadGrid');
    });
    //保存
    $("#employeeSaveBtn").click(function () {
        if (form.form()) {
            doSubmit();
        }
    });

    $("#departmentEditBtn").click(function () {
        if (form1.form()) {
            doSubmit1();
        }
    });

    $(".select2").select2({
        allowClear: true
    });
});

//设置cookie
var setCookie = function (name, value, day) {
    //当设置的时间等于0时，不设置expires属性，cookie在浏览器关闭后删除
    var expires = day * 24 * 60 * 60 * 1000;
    var exp = new Date();
    exp.setTime(exp.getTime() + expires);
    document.cookie = name + "=" + value + ";expires=" + exp.toUTCString();
};

function turnOut(obj) {
    setCookie('id', obj);
    loadPage("customerManager/message.html");
}

//打开新建表单(弹出框)
function openAdd() {
    clearForm();
    $("#myModal").modal();
    $("#myModeltitle").html("新建");

}

//打开新建表单(新页面)
function openNewAdd() {
    loadPage("person/userAdd.html");
}

//打开编辑表单
function openEdit(str) {
    array = str.split(",");
    $("#editmyModal").modal();
    $("#modeltitle").html("编辑");
    $("#departmentId").val(array[0]);
    $("#department").val(array[1]);
}

function deleteEdit(obj) {
    if (confirm("确认删除此条记录吗?")) {
        $.ajax({
            url: "delete?delId=" + obj,
            type: "post",
            success: function (data) {

            }
        })
    }
}

//删除记录
function openDelete(str) {
    array = str.split(",");
    bootbox.confirm("您确定要将删除此行记录吗?", function (result) {
        if (result) {
            $.post("deleteDepartment", {
                "departmentId": array[0],
                "departmentName": array[1]
            }, function (data) {
                alert(data.resultMessage);
                grid.trigger('reloadGrid');
            });
        }
    });
}

//提交表单
function doSubmit() {
    $("#loading").removeClass('hide').addClass('show');
    $.post("addDepartment", $('#addform').serialize(), function (data) {
        if (data.resultCode == 201) {
            $("#loading").removeClass('show').addClass('hide');
            alert(data.resultMessage);
        } else if (data.resultCode == 202) {
            $("#loading").removeClass('show').addClass('hide');
            alert(data.resultMessage);
        } else {
            $("#loading").removeClass('show').addClass('hide');
            alert("添加成功!");
            grid.trigger('reloadGrid');
            $('#addmyModal').modal('hide');
        }
    });
}

//提交编辑
function doSubmit1() {
    alert($('#Editform').serialize());
    $("#loading").removeClass('hide').addClass('show');
    $.post("updateDepartment", $('#Editform').serialize(), function (data) {
        alert(123);
        if (data.resultCode == 201) {
            $("#loading").removeClass('show').addClass('hide');
            alert(data.resultMessage);
        } else {
            alert("编辑成功!");
            grid.trigger('reloadGrid');
            $('#editmyModal').modal('hide');
            $("#loading").removeClass('show').addClass('hide');
        }
    });
}

//清除表单
function clearForm() {
    //清空内容
    $("#tel").val("");
    $("#ename").val("");
    $("#men").removeAttr("checked");
    $("#men1").removeAttr("checked");
    $("#women1").removeAttr("checked");
    $("#women").removeAttr("checked");
    $("#birthday").val("");
    //清除验证状态

    $("#addform .form-group").removeClass('has-info').removeClass('has-error');

}

function getPositionNames() {
    $.post("positionList", {}, function (data) {
        for (var i = 0; i < data.data.length; i++) {
            $("#positionName").append('<option  value=' + data.data[i].positionName + '>' + data.data[i].positionName + '</option>');
        }
    });
}